<?php

namespace Anchu\Cockpit\Middlewares;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class PlatformLoginAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $sign = $request->header('Authorization');
        $sign = substr($sign, 7);
        $cacheSignValue = Cache::get($sign);
        if (empty($cacheSignValue)) {
            return response()->json([
                'code' => '401',
                'msg' => '登录过期，请重新登录',
            ])->setStatusCode(401);
        }
        $cacheSign = md5('login:' . $cacheSignValue['operatorId'] . ':' . $cacheSignValue['mobile'] . ':' . $cacheSignValue['timestamp']);
        if ($sign != $cacheSign) {
            return response()->json([
                'code' => '401',
                'msg' => '登录过期，请重新登录',
            ])->setStatusCode(401);
        }
        $expired = env('PLATFORM_LOGIN_EXPIRED', 24 * 3600);
        Cache::put($sign, $cacheSignValue, $expired);
        return $next($request);
    }
}
